package net.wantongtech.xa.uploadbasicinfo.service;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.wtkj.vo.dzzf.base.xxdl.InteractionOrgMsgReceive;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.config.SCPClientConfig;
import net.wantongtech.xa.uploadbasicinfo.dao.DealWithMissingTransPackageDao;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理缺失交易包的数据服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/2
 */
@Slf4j
@Service
public class DealWithMissingTransPackageService {

    @Resource
    private SCPClientConfig scpClientConfig;

    @Resource
    private DealWithMissingTransPackageDao dealWithMissingTransPackageDao;

    private List<String> fileNameList;

    @PostConstruct
    public void init() {
        String localStorePath = scpClientConfig.getLocalStorePath();
        File[] jsonFileArr = new File(localStorePath).listFiles((dir, name) -> name.endsWith(".json"));
        if (!ArrayUtils.isEmpty(jsonFileArr)) {
            this.fileNameList = Arrays.stream(jsonFileArr)
                    .map(File::getName)
                    .collect(Collectors.toList());
        } else {
            this.fileNameList = Lists.newArrayList();
        }
    }


    public void process() {


        List<String> receiveIdList = dealWithMissingTransPackageDao.queryMissingTransPackageReceiveId();
        log.info("共查询出{}条待处理的接收表记录", receiveIdList.size());
        if (receiveIdList.isEmpty()) {
            return;
        }
        receiveIdList.forEach(this::processSingle);

    }

    @SuppressWarnings("unused")
    private void processSingleV2(String receiveId) {
        InteractionOrgMsgReceive ormObj = new InteractionOrgMsgReceive();
        ormObj.setListID(receiveId);
        InteractionOrgMsgReceive receiveMsg = (InteractionOrgMsgReceive) dealWithMissingTransPackageDao.queryObject(ormObj);
        if (receiveMsg == null) {
            log.error("ListId为【{}】的接收表记录不存在", receiveId);
            return;
        }
        String storePath = receiveMsg.getStorePath();
        String fileName = storePath.substring(storePath.lastIndexOf('/') + 1);
        if (fileNameList.contains(fileName)) {
            File targetFile = new File(scpClientConfig.getLocalStorePath(), fileName);
            log.info("包含文件名：{}，目标文件路径：{}", fileName, targetFile.getAbsoluteFile());
            ormObj.setStoreFlag(InteractionOrgMsgReceive.STORE_FLAG_DISK);
            String absolutePath = targetFile.getAbsolutePath();
            ormObj.setStorePath(absolutePath);
            dealWithMissingTransPackageDao.updateObject(ormObj);
        }
    }


    @SuppressWarnings("UnstableApiUsage")
    private void processSingle(String receiveId) {
        InteractionOrgMsgReceive ormObj = new InteractionOrgMsgReceive();
        ormObj.setListID(receiveId);
        InteractionOrgMsgReceive receiveMsg = (InteractionOrgMsgReceive) dealWithMissingTransPackageDao.queryObject(ormObj);
        if (receiveMsg == null) {
            log.error("ListId为【{}】的接收表记录不存在", receiveId);
            return;
        }
        log.info("开始处理ListId为【{}】的接收表数据", receiveId);
        String storePath = receiveMsg.getStorePath();
        String subPath = storePath.substring(storePath.indexOf('/') + 1);
        String filePath = String.format("%s/%s", scpClientConfig.getPrefixPath(), subPath);
        String fileName = storePath.substring(storePath.lastIndexOf('/') + 1);
        log.info("文件路径：{}，文件名：{}", filePath, fileName);

        Connection connection = new Connection(scpClientConfig.getHost(), scpClientConfig.getPort());
        try {
            connection.connect();
            try {
                boolean isAuthenticated = connection.authenticateWithPassword(scpClientConfig.getUsername(),
                        scpClientConfig.getPassword());
                if (!isAuthenticated) {
                    log.error("服务器身份认证失败");
                    return;
                }

                SCPClient scpClient = connection.createSCPClient();

                SCPInputStream scpInputStream = scpClient.get(filePath);
                File localFile = new File(scpClientConfig.getLocalStorePath(), fileName);
                try (BufferedWriter localFileWriter = Files.newWriter(localFile, Charset.forName("UTF-8"))) {
                    IOUtils.write(IOUtils.toByteArray(scpInputStream), localFileWriter, "UTF-8");
                }
                String localFilePath = localFile.getAbsolutePath();
                log.info("本地文件{}保存成功", localFilePath);

                ormObj.setStoreFlag(InteractionOrgMsgReceive.STORE_FLAG_DISK);
                ormObj.setStorePath(localFilePath);
                dealWithMissingTransPackageDao.updateObject(ormObj);

            } finally {
                connection.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }


    }


}
